package cn.itheima.action.takedelivery;

import cn.itheima.action.common.BaseAction;
import cn.itheima.domain.Promotion;
import cn.itheima.service.takedelivery.PromotionService;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by millions on 2017/7/7.
 */
@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class PromotionAction extends BaseAction<Promotion>{

    private File titleImgFile;

    private String titleImgFileFileName;

    public void setTitleImgFileFileName(String titleImgFileFileName) {
        this.titleImgFileFileName = titleImgFileFileName;
    }
    public void setTitleImgFile(File titleImgFile) {
        this.titleImgFile = titleImgFile;
    }


    @Autowired
    private PromotionService promotionService;

    @Action(value = "save_promotion",results = {
            @Result(type = "redirect",location = "./pages/take_delivery/promotion.html"),
            @Result(name = "input",location = "./error.jsp")})
    public String savePromotion() throws IOException {

        String realPath = ServletActionContext.getServletContext().getRealPath("/upload");
        String returnUrl = ServletActionContext.getRequest().getContextPath() + "/upload/";

        //生成随机的文件文名
        String randomFileName = UUID.randomUUID()+titleImgFileFileName.substring(titleImgFileFileName.lastIndexOf("."));
        //保存文件
        FileUtils.copyFile(titleImgFile,new File(realPath+"/"+randomFileName));

        model.setTitleImg(returnUrl+randomFileName);

        promotionService.save(model);

        return SUCCESS;
    }

    @Action(value = "query_promotion",results = {@Result(type = "json")})
    public String pageQuery(){

        Pageable pageable=new PageRequest(page-1,rows);
        Page<Promotion> promotionPage=promotionService.queryPage(pageable);
        pushPageDataToValueStack(promotionPage);

        return SUCCESS;
    }

}
